package com.leo.javase.thread.itcast;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 子线程循环10次，接着主线程循环100，接着又回到子线程循环10次，接着再回到主线程又循环100，如此循环50次
 * @author Lian
 */
public class ConditionCommunicate {

	public static void main(String[] args) {
		final Business bs = new Business();
		
		//子线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<5; i++){
					bs.sub(i);
				}
			}
		}).start();
		
		//主线程
		for(int i=0; i<5; i++){
			bs.main(i);
		}
	}
}
class Business{
	private boolean flag = true;
	
	private Lock lock = new ReentrantLock();
	
	Condition condition = lock.newCondition();
	/**
	 * 子线程
	 * @param i
	 */
	public void sub(int i){
		lock.lock();
		try{
			while(!flag){
				try {
					condition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for(int j=0; j<5; j++){
				System.out.println("Sub thread i="+(i+1)+",j="+(j+1));
			}
			
			flag = false;
			condition.signal();
		}finally{
			lock.unlock();
		}
	}
	/**
	 * 主线程
	 * @param i
	 */
	public void main(int i){
		lock.lock();
		try{
			while(flag){
				try {
					condition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			for(int j=0; j<10; j++){
				System.out.println("Main thread i="+(i+1)+",j="+(j+1));
			}
			
			flag = true;
			condition.signal();
		}finally{
			lock.unlock();
		}
	}
}
